import React, { useEffect, useState, useContext } from 'react';
import { Upload, message, Button, Icon } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { styled } from 'styled-components';
import { StatusContext } from '@/views/MaterialsView/context';
import { observer } from 'mobx-react-lite';
const Container = styled.div`
  .container {
    width: 200px;
    height: 300px;
    border: 1px solid var(--font-color-lightest);
    border-radius: var(--border-radius-md);
    color: var(--font-color-light);
    > .top {
      width: 100%;
      height: 200px;
      background-color: var(--font-color-lightest);
    }
    > .bottom {
      height: 100px;
      font-size: var(--font-size-lg);
      > .desc {
        font-size: var(--font-size-base);
        color: var(--font-color-light);
      }
    }
  }
  .avatar {
    width: 200px;
    height: 200px;
    object-fit: contain;
  }
`;

interface PicItemProps {
  picTitle: string;
  picDesc: string;
  value: string;
  index: number;
}

const PicItem: React.FC<PicItemProps> = observer(({ picTitle, picDesc, value, index }) => {
  console.log('进入', value, index);
  const [imageUrl, setImageUrl] = useState<string>('');
  const { updateStatus } = useContext(StatusContext);

  useEffect(() => {
    const fetchImage = async () => {
      if (value) {
        try {
          const res = await fetch(value);
          const blob = await res.blob();
          const file = new File([blob], 'image.jpg', { type: blob.type });
          const url = URL.createObjectURL(file);
          console.log(url, 'uuuuuu');
          setImageUrl(url);
        } catch (error) {
          console.error('Error fetching image:', error);
        }
      } else {
        setImageUrl('');
      }
    };

    fetchImage();
  }, [value]);

  const handleAvatarSuccess = (info: any) => {
    console.log('上传成功', info);
    updateStatus('options', { index, value: info.imageUrl });
  };

  const beforeAvatarUpload = (file: File) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
  };

  return (
    <Container onClick={e => e.stopPropagation()}>
      <div className="container m-b-2">
        {/* 添加图片 */}
        <div className="top flex justify-center items-center">
          <Upload
            name="image"
            action="/api/upload"
            showUploadList={false}
            onSuccess={handleAvatarSuccess}
            beforeUpload={beforeAvatarUpload}>
            {imageUrl ? (
              <img src={imageUrl} alt="avatar" className="avatar" />
            ) : (
              <Button icon={<UploadOutlined />}>添加图片</Button>
            )}
          </Upload>
        </div>
        {/* 图片标题和描述 */}
        <div className="bottom flex justify-center items-center flex-col">
          <div className="item">{picTitle}</div>
          <div className="desc m-t-1 m-b-1">{picDesc}</div>
        </div>
      </div>
    </Container>
  );
});

export default PicItem;
